package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.business.constant.IBusinessConstant;
import com.ruoyi.business.domain.*;
import com.ruoyi.business.mapper.BusinessComponentMapper;
import com.ruoyi.business.mapper.TenantFunctionVersionMapper;
import com.ruoyi.business.service.IBusinessComponeParametersVersionService;
import com.ruoyi.business.service.IBusinessComponentReturnValueVersionService;
import com.ruoyi.business.service.IBusinessComponentService;
import com.ruoyi.business.service.ISysFunctionService;
import com.ruoyi.common.core.context.SecurityContextHolder;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.UniqueIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 业务组件Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-04
 */
@Service
@Slf4j
public class BusinessComponentServiceImpl implements IBusinessComponentService
{
    @Autowired
    private BusinessComponentMapper businessComponentMapper;
    @Autowired
    private IBusinessComponeParametersVersionService businessComponeParametersVersionService;
    @Autowired
    private TenantFunctionVersionMapper tenantFunctionVersionMapper;
    @Autowired
    private ISysFunctionService sysFunctionService;
    @Autowired
    private IBusinessComponentReturnValueVersionService businessComponentReturnValueVersionService;
    /**
     * 查询业务组件
     *
     * @param id 业务组件主键
     * @return 业务组件
     */
    @Override
    public BusinessComponent selectBusinessComponentById(Long id)
    {
        return businessComponentMapper.selectBusinessComponentById(id);
    }

    /**
     * 查询业务组件列表
     *
     * @param businessComponent 业务组件
     * @return 业务组件
     */
    @Override
    public List<BusinessComponent> selectBusinessComponentList(BusinessComponent businessComponent)
    {
        return businessComponentMapper.selectBusinessComponentList(businessComponent);
    }

    /**
     * 新增业务组件
     *
     * @param businessComponent 业务组件
     * @return 结果
     */
    @Override
    public int insertBusinessComponent(BusinessComponent businessComponent)
    {
        businessComponent.setCreateTime(DateUtils.getNowDate());
        //自动产生组件编码，并保证唯一
        String code;
        BusinessComponent searchBusinessComponent = new BusinessComponent();
        while (true) {
            code = UniqueIdGenerator.getUniqueClassName(10);
            searchBusinessComponent.setComponentCode( code);
            List<BusinessComponent> list = businessComponentMapper.selectBusinessComponentList(searchBusinessComponent);
            if (list.size() == 0) {
                businessComponent.setComponentCode(code);
                break;
            }
        }
        return businessComponentMapper.insertBusinessComponent(businessComponent);
    }

    /**
     * 修改业务组件
     *
     * @param businessComponent 业务组件
     * @return 结果
     */
    @Override
    public int updateBusinessComponent(BusinessComponent businessComponent)
    {
        businessComponent.setUpdateTime(DateUtils.getNowDate());
        return businessComponentMapper.updateBusinessComponent(businessComponent);
    }

    /**
     * 批量删除业务组件
     *
     * @param ids 需要删除的业务组件主键
     * @return 结果
     */
    @Override
    public int deleteBusinessComponentByIds(Long[] ids)
    {
        return businessComponentMapper.deleteBusinessComponentByIds(ids);
    }

    /**
     * 删除业务组件信息
     *
     * @param id 业务组件主键
     * @return 结果
     */
    @Override
    public int deleteBusinessComponentById(Long id)
    {
        return businessComponentMapper.deleteBusinessComponentById(id);
    }

    /**
     * 提交新增
     *
     * @param businessComponentComposite
     * @return
     */
    @Override
    public Long commitAdd(BusinessComponentComposite businessComponentComposite) {
        //校验基本信息
        verifyInsertMain(businessComponentComposite.getBusinessComponent());
        //校验参数信息
        verifyInsertBussinessComponentParametersVersion(businessComponentComposite.getBusinessComponeParametersVersions());
        //填充默认值
        fillInsertDefaultValues(businessComponentComposite);
        //插入基本信息
        businessComponentMapper.insertBusinessComponent(businessComponentComposite.getBusinessComponent());
        //生成groovy脚本
        businessComponentComposite.getBusinessComponent().setGroovySource(makeGroovySource(businessComponentComposite));
        //插入参数信息
        for(BusinessComponeParametersVersion businessComponeParametersVersion:businessComponentComposite.getBusinessComponeParametersVersions()){
            businessComponeParametersVersionService.insertBusinessComponeParametersVersion(businessComponeParametersVersion);
        }
        return businessComponentComposite.getBusinessComponent().getId();

    }


    /**
     * 生成groovy脚本（优化版本，移除循环逻辑）
     * @param businessComponentComposite
     * @return
     */
    private String makeGroovySource(BusinessComponentComposite businessComponentComposite) {
        String jsonStr = businessComponentComposite.getBusinessComponent().getDesignScript();
        JSONObject jsonObject = JSON.parseObject(jsonStr);

        // 1. 收集所有组件和菱形框
        Map<String, JSONObject> components = new HashMap<>();
        Map<String, JSONObject> diamonds = new HashMap<>();

        JSONArray svgElements = jsonObject.getJSONArray("svgElements");
        JSONArray diamondElements = jsonObject.getJSONArray("diamondElements");
        JSONArray connections = jsonObject.getJSONArray("connections");

        // 2. 索引所有元素
        indexElements(svgElements, components);
        indexElements(diamondElements, diamonds);

        // 提取所有子功能点groovy源码
        List<String> childGroovySource = pickChildGroovySource(svgElements);
        // 生成import段
        String importSegs = mergeOnlyImports(childGroovySource);

        // 3. 构建执行流程图
        StringBuilder groovy = new StringBuilder();
        groovy.append(importSegs);
        groovy.append("def ").append(businessComponentComposite.getBusinessComponent().getComponentCode()).append("(").
                append(makeGroovyFunctionParams(businessComponentComposite.getBusinessComponeParametersVersions()))
                .append(")")
                .append(" {\n");

        // 4. 查找起始组件（无入连接的组件）
        Set<String> componentIds = new HashSet<>(components.keySet());
        String startComponentId = findStartComponent(connections, componentIds);
        if (startComponentId == null) {
            throw new RuntimeException("未找到起始组件");
        }

        // 5. 生成开始节点（移除循环分析）
        Set<String> processed = new HashSet<>();
        generateComponentCode(startComponentId, components, diamonds, connections,
                groovy, processed);

        groovy.append("}\n");
        return groovy.toString();
    }
    // 核心方法：递归生成组件代码（移除循环相关逻辑）
    private void generateComponentCode(String elementId,
                                       Map<String, JSONObject> components,
                                       Map<String, JSONObject> diamonds,
                                       JSONArray connections,
                                       StringBuilder groovy,
                                       Set<String> processed) {
        // 正常处理组件
        generateComponentBody(elementId, components, diamonds, connections,
                groovy, processed);
    }
    // 辅助方法：查找起始组件
    private String findStartComponent(JSONArray connections, Set<String> componentIds) {
        Set<String> hasIncoming = new HashSet<>();
        for (int i = 0; i < connections.size(); i++) {
            JSONObject conn = connections.getJSONObject(i);
            hasIncoming.add(conn.getString("endElementId"));
        }
        componentIds.removeAll(hasIncoming);
        return componentIds.isEmpty() ? null : componentIds.iterator().next();
    }
    // 辅助方法：索引元素
    private void indexElements(JSONArray elements, Map<String, JSONObject> map) {
        for (int i = 0; i < elements.size(); i++) {
            JSONObject element = elements.getJSONObject(i);
            map.put(element.getString("id"), element);
        }
    }
    /**
     * 填充默认值
     * @param businessComponentComposite
     */
    private void fillInsertDefaultValues(BusinessComponentComposite businessComponentComposite) {
        //基本信息
        businessComponentComposite.getBusinessComponent().setVersion(1);
        businessComponentComposite.getBusinessComponent().setIsCurrent("Y");
        businessComponentComposite.getBusinessComponent().setEnterpriseCode(SecurityContextHolder.getEnterpriseCode());
        //设置状态为已提交
        businessComponentComposite.getBusinessComponent().setStatus(IBusinessConstant.STATUS_SUBMIT);
        businessComponentComposite.getBusinessComponent().setCreateBy(SecurityContextHolder.getUserName());
        businessComponentComposite.getBusinessComponent().setCreateTime(DateUtils.getNowDate());
        businessComponentComposite.getBusinessComponent().setComponentCode(getNewComponentCode());
        //参数表信息
        for(BusinessComponeParametersVersion businessComponeParametersVersion:businessComponentComposite.getBusinessComponeParametersVersions()){
            businessComponeParametersVersion.setVersion(1);
            businessComponeParametersVersion.setParameterId(null);
            businessComponeParametersVersion.setEnterpriseCode(SecurityContextHolder.getEnterpriseCode());
            businessComponeParametersVersion.setCreateBy(SecurityContextHolder.getUserName());
            businessComponeParametersVersion.setCreateTime(DateUtils.getNowDate());
            businessComponeParametersVersion.setComponentCode(businessComponentComposite.getBusinessComponent().getComponentCode());
            businessComponeParametersVersion.setIsCurrent("Y");
            businessComponeParametersVersion.setParameterCode(getNewParameterCode());
        }
    }

    private String getNewParameterCode() {
        String parameterCode="";
        while (true){
            parameterCode = UniqueIdGenerator.getUniqueClassName(10);
            BusinessComponeParametersVersion searchBusinessComponeParametersVersion = new BusinessComponeParametersVersion();
            searchBusinessComponeParametersVersion.setParameterCode(parameterCode);
            List<BusinessComponeParametersVersion> list = businessComponeParametersVersionService.selectBusinessComponeParametersVersionList(searchBusinessComponeParametersVersion);
            if(list.size()==0)
                break;
        }
        return parameterCode;
    }

    /**
     * 获取新的业务组件编码
     * @return
     */
    private String getNewComponentCode() {
        String componentCode="";
        while (true){
            componentCode = UniqueIdGenerator.getUniqueClassName(10);
            BusinessComponent searchBusinessComponent = new BusinessComponent();
            searchBusinessComponent.setComponentCode(componentCode);
            List<BusinessComponent> list = businessComponentMapper.selectBusinessComponentList(searchBusinessComponent);
            if(list.size()==0)
                break;
        }
        return componentCode;
    }

    /**
     * 校验业务组件参数信息
     * @param businessComponeParametersVersions
     */
    private void verifyInsertBussinessComponentParametersVersion(List<BusinessComponeParametersVersion> businessComponeParametersVersions) {
        if(businessComponeParametersVersions==null)
            throw new RuntimeException("业务组件参数版本表不能为空");
        int index =0;
        for(BusinessComponeParametersVersion businessComponeParametersVersion:businessComponeParametersVersions){
            if(businessComponeParametersVersion==null)
                throw new RuntimeException("业务组件参数版本表不能为空");
            if(StringUtils.isEmpty(businessComponeParametersVersion.getParameterType()))
                throw new RuntimeException("业务组件参数版本表参数类型不能为空");
            //参数描述不能重复
            if(isRepeatParameterDesc(businessComponeParametersVersions,businessComponeParametersVersion,index))
                throw new RuntimeException("业务组件参数版本表参数描述不能重复");
            index++;
        }
    }
    /**
     * 判断参数描述是否重复
     * @param businessComponeParametersVersions
     * @param businessComponeParametersVersion
     * @param index
     * @return
     */
    private boolean isRepeatParameterDesc(List<BusinessComponeParametersVersion> businessComponeParametersVersions, BusinessComponeParametersVersion businessComponeParametersVersion, int index) {
        for(int i=0;i<businessComponeParametersVersions.size();i++){
            if(i==index)
                continue;
            if(businessComponeParametersVersions.get(i).getParameterDesc().equals(businessComponeParametersVersion.getParameterDesc()))
                return true;
        }
        return false;
    }

    /**
     * 校验插入主信息
     * @param businessComponent
     */
    private void verifyInsertMain(BusinessComponent businessComponent) {
        if(businessComponent==null)
            throw new ServiceException("无效的参数");
        if(StringUtils.isEmpty(businessComponent.getComponentName()))
            throw new ServiceException("组件名称为空");
        if(StringUtils.isEmpty(businessComponent.getComponentIconUrl()))
            throw new ServiceException("组件图标为空");
        //组件设计脚本不能为空
        if(StringUtils.isEmpty(businessComponent.getDesignScript()))
            throw new ServiceException("组件设计脚本不能为空");
        //是否有返回值不能为空
        if(StringUtils.isEmpty(businessComponent.getIsReturnvalue()))
            throw new ServiceException("是否有返回值不能为空");
        //返回值类型不能为空
        if(StringUtils.isEmpty(businessComponent.getReturnType()))
                throw new ServiceException("返回值类型不能为空");

    }

    /**
     * 提交修改
     *
     * @param businessComponentComposite
     * @return
     */
    @Override
    public Long commitUpdate(BusinessComponentComposite businessComponentComposite) {
        //校验基本信息
        verifyUpdateMain(businessComponentComposite.getBusinessComponent());
        //校验功能点参数信息
        verifyUpdateBusinessComponentParametersVersion(businessComponentComposite.getBusinessComponeParametersVersions(),businessComponentComposite);
        //判断主表状态是否为已提交，如果是则版本号+1
        if(IBusinessConstant.STATUS_SUBMIT.equals(businessComponentComposite.getBusinessComponent().getStatus())) {
            //更新其他版本为非当前版本
            updateCurrentVersionToIsNot(
                    businessComponentComposite.getBusinessComponent().getComponentCode(),
                    businessComponentComposite.getBusinessComponent().getEnterpriseCode());
            //更新功能参数当前版本标志设置为非当前
            businessComponeParametersVersionService.updateCurrentVersionToIsNot(
                    businessComponentComposite.getBusinessComponent().getComponentCode(),
                    businessComponentComposite.getBusinessComponent().getEnterpriseCode());

            //填充版本号：最大版本号+1
            fillUpdateDefaultValues(businessComponentComposite);

            //更新基本信息
            if(businessComponentComposite.getBusinessComponent().getSortNumber()==null){
                businessComponentComposite.getBusinessComponent().setSortNumber(1);
            }
            //生成groovy脚本
            businessComponentComposite.getBusinessComponent().setGroovySource(makeGroovySource(businessComponentComposite));
            businessComponentMapper.insertBusinessComponent(businessComponentComposite.getBusinessComponent());
            //删除原来参数，再插入参数
            businessComponeParametersVersionService.deleteParametersVersionByComponentCode(
                    businessComponentComposite.getBusinessComponent().getComponentCode(),
                    businessComponentComposite.getBusinessComponent().getEnterpriseCode(),
                    businessComponentComposite.getBusinessComponent().getVersion()
            );
            //插入当前提交信息为当前版本
            for (BusinessComponeParametersVersion businessComponeParametersVersion : businessComponentComposite.getBusinessComponeParametersVersions()) {
                //去掉ID,防止主键重复
                businessComponeParametersVersion.setParameterId(null);
                businessComponeParametersVersionService.insertBusinessComponeParametersVersion(businessComponeParametersVersion);
            }
        }else{
            //状态改成已提交
            businessComponentComposite.getBusinessComponent().setStatus(IBusinessConstant.STATUS_SUBMIT);
            //生成groovy脚本
            businessComponentComposite.getBusinessComponent().setGroovySource(makeGroovySource(businessComponentComposite));
            businessComponentComposite.getBusinessComponent().setIsCurrent("Y");
            //更新基本信息
            businessComponentMapper.updateBusinessComponent(businessComponentComposite.getBusinessComponent());

            //删除原来参数，再插入参数
            businessComponeParametersVersionService.deleteParametersVersionByComponentCode(
                    businessComponentComposite.getBusinessComponent().getComponentCode(),
                    businessComponentComposite.getBusinessComponent().getEnterpriseCode(),
                    businessComponentComposite.getBusinessComponent().getVersion()
            );
            for (BusinessComponeParametersVersion businessComponeParametersVersion : businessComponentComposite.getBusinessComponeParametersVersions()) {
                //去掉ID,防止主键重复
                businessComponeParametersVersion.setParameterId(null);
                businessComponeParametersVersionService.insertBusinessComponeParametersVersion(businessComponeParametersVersion);
            }
        }
        return businessComponentComposite.getBusinessComponent().getId();
    }

    /**
     * 填充更新默认值
     * @param businessComponentComposite
     */
    private void fillUpdateDefaultValues(BusinessComponentComposite businessComponentComposite) {
        int newVersion = businessComponentComposite.getBusinessComponent().getVersion()+1;
        //设置状态为提交
        businessComponentComposite.getBusinessComponent().setStatus(IBusinessConstant.STATUS_SUBMIT);
        businessComponentComposite.getBusinessComponent().setVersion(newVersion);
        businessComponentComposite.getBusinessComponent().setIsCurrent(IBusinessConstant.SYSTEM_YES);
        businessComponentComposite.getBusinessComponent().setVersion(newVersion);
        if(StringUtils.isEmpty(businessComponentComposite.getBusinessComponent().getEnterpriseCode())){
            businessComponentComposite.getBusinessComponent().setEnterpriseCode(businessComponentComposite.getBusinessComponent().getEnterpriseCode());
        }
        if(StringUtils.isEmpty(businessComponentComposite.getBusinessComponent().getCreateBy())){
            businessComponentComposite.getBusinessComponent().setCreateBy(SecurityContextHolder.getUserName());
        }
        if(StringUtils.isEmpty(businessComponentComposite.getBusinessComponent().getUpdateBy())){
            businessComponentComposite.getBusinessComponent().setUpdateBy(SecurityContextHolder.getUserName());
        }
        businessComponentComposite.getBusinessComponent().setUpdateTime(DateUtils.getNowDate());
        businessComponentComposite.getBusinessComponent().setCreateTime(DateUtils.getNowDate());
        //更新参数列表
        for(BusinessComponeParametersVersion businessComponeParametersVersion:businessComponentComposite.getBusinessComponeParametersVersions()){
            businessComponeParametersVersion.setVersion(newVersion);
            businessComponeParametersVersion.setIsCurrent(IBusinessConstant.SYSTEM_YES);
            if(StringUtils.isEmpty(businessComponeParametersVersion.getComponentCode())){
                businessComponeParametersVersion.setComponentCode(businessComponentComposite.getBusinessComponent().getComponentCode());
            }
            if(StringUtils.isEmpty(businessComponeParametersVersion.getCreateBy())){
                businessComponeParametersVersion.setCreateBy(SecurityContextHolder.getUserName());
            }
            businessComponeParametersVersion.setUpdateBy(SecurityContextHolder.getUserName());
            businessComponeParametersVersion.setUpdateTime(DateUtils.getNowDate());
        }
    }
    /**
     * 更新当前版本为非当前版本
     * @param componentCode
     * @param enterpriseCode
     */
    private void updateCurrentVersionToIsNot(String componentCode, String enterpriseCode) {
        businessComponentMapper.updateCurrentVersionToIsNot(componentCode,enterpriseCode);
    }

    /**
     * 校验更新业务组件参数信息
     * @param businessComponeParametersVersions
     * @param businessComponentComposite
     */
    private void verifyUpdateBusinessComponentParametersVersion(List<BusinessComponeParametersVersion> businessComponeParametersVersions, BusinessComponentComposite businessComponentComposite) {
        int index=0;
        for(BusinessComponeParametersVersion businessComponeParametersVersion:businessComponeParametersVersions){
            if(businessComponeParametersVersion==null)
                throw new RuntimeException("业务组件参数版本表不能为空");
            if(StringUtils.isEmpty(businessComponeParametersVersion.getParameterName()))
                throw new RuntimeException("业务组件参数版本表参数名称不能为空");
            //tenantFunctionParametersVersions列表中参数名称不能重复
            if(isRepeatParameterDesc(businessComponeParametersVersions,businessComponeParametersVersion,index))
                throw new RuntimeException("业务组件参数版本表参数名称："+businessComponeParametersVersion.getParameterName()+"不能重复");

            if(StringUtils.isEmpty(businessComponeParametersVersion.getParameterType()))
                throw new RuntimeException("业务组件参数版本表参数类型不能为空");
            if(StringUtils.isEmpty(businessComponeParametersVersion.getParameterCode())){
                businessComponeParametersVersion.setParameterCode(getNewParameterCode());
            }
            if(StringUtils.isEmpty(businessComponeParametersVersion.getEnterpriseCode())){
                businessComponeParametersVersion.setEnterpriseCode(businessComponentComposite.getBusinessComponent().getEnterpriseCode());
            }

            if(StringUtils.isEmpty(businessComponeParametersVersion.getIsCurrent())){
                businessComponeParametersVersion.setIsCurrent(businessComponentComposite.getBusinessComponent().getIsCurrent());
            }

            if(!IBusinessConstant.SYSTEM_YES.equals(businessComponeParametersVersion.getIsCurrent()) &&
                    !IBusinessConstant.SYSTEM_NO.equals(businessComponeParametersVersion.getIsCurrent())
            )
                businessComponeParametersVersion.setIsCurrent(businessComponentComposite.getBusinessComponent().getIsCurrent());
            index++;
        }
    }

    /**
     * 校验更新主信息
     * @param businessComponent
     */
    private void verifyUpdateMain(BusinessComponent businessComponent) {
        if(businessComponent==null)
            throw new RuntimeException("业务组件不能为空");
        if(StringUtils.isEmpty(businessComponent.getComponentName()))
            throw new RuntimeException("业务组件组件名称不能为空");
        if(StringUtils.isEmpty(businessComponent.getComponentIconUrl()))
            throw new ServiceException("组件图标为空");
        //组件设计脚本不能为空
        if(StringUtils.isEmpty(businessComponent.getDesignScript()))
            throw new ServiceException("组件设计脚本不能为空");
        //是否有返回值不能为空
        if(StringUtils.isEmpty(businessComponent.getIsReturnvalue()))
            throw new ServiceException("是否有返回值不能为空");
        //返回值类型不能为空
        if(StringUtils.isEmpty(businessComponent.getReturnType()))
                throw new ServiceException("返回值类型不能为空");

        if(StringUtils.isEmpty(businessComponent.getEnterpriseCode()))
            throw new RuntimeException("业务组件企业编码不能为空");
        if(StringUtils.isEmpty(businessComponent.getStatus()))
            throw new RuntimeException("业务组件状态不能为空");

        if(businessComponent.getVersion()==0)
            throw new RuntimeException("业务组件版本号不能为空");
        if(businessComponent.getId()==0)
            throw new RuntimeException("业务组件ID不能为空");
    }



    /**
     * 构造groovy函数参数
     * @param businessComponeParametersVersions
     * @return
     */
    private String makeGroovyFunctionParams(List<BusinessComponeParametersVersion> businessComponeParametersVersions) {
        StringBuilder params = new StringBuilder("");
        for(BusinessComponeParametersVersion businessComponeParametersVersion:businessComponeParametersVersions){
            params.append(businessComponeParametersVersion.getParameterName()).append(",");
        }
        return params.toString().isEmpty() ? "" :  params.substring(0, params.length() - 1) ;
    }


    /**
     * 提取子功能点groovy源码
     * @param svgElements
     * @return
     */
    private List<String> pickChildGroovySource(JSONArray svgElements) {
        List<String> sources = new ArrayList<>();
        for (int i = 0; i < svgElements.size(); i++) {
            JSONObject element = svgElements.getJSONObject(i);
            JSONArray children = element.getJSONArray("children");
            String objectType = element.getString("objectType");
            //只处理组件
            if (IBusinessConstant.NODE_TYPE_COMPONENT.equals(objectType)) {
                if (children != null && children.size() > 2) {
                    JSONObject firstChild = children.getJSONObject(2);
                    JSONObject attrs = firstChild.getJSONObject("attrs");
                    String className = attrs.getString("className");
                    //是否为租户函数（功能点），默认为否(N)
                    String isTenant = attrs.getString("isTenant");
                    if ("Y".equals(isTenant)) {
                        TenantFunctionVersion tenantFunctionVersion = tenantFunctionVersionMapper.getTenantFunctionByClassName(className);
                        if (tenantFunctionVersion != null) {
                            sources.add(tenantFunctionVersion.getGroovySource());
                        } else
                            throw new RuntimeException("未找到类：" + className + "租户组件功能点版本表或者该类已经禁用！");
                    } else {
                        SysFunction sysFunction = sysFunctionService.getSysFunctionByClassName(className);
                        if (sysFunction != null) {
                            sources.add(sysFunction.getGroovySource());
                        } else
                            throw new RuntimeException("未找到类：" + className + "系统功能表或者该类已经禁用");
                    }
                }
            }
        }
        return sources;
    }
    /**
     * 合并多个Groovy脚本的import语句（去重）
     * @param sources 原始脚本列表
     * @return 合并后的import段 + 原始代码（保持不变）
     */
    public String mergeOnlyImports(List<String> sources) {
        Set<String> imports = new LinkedHashSet<>();
        // 匹配：import [static] pkg.Class [;]
        Pattern pattern = Pattern.compile(
                "^\\s*import\\s+(?:static\\s+)?([\\w.]+(?:\\.[\\w*]+)*)\\s*;?",
                Pattern.MULTILINE
        );

        for (String source : sources) {
            Matcher matcher = pattern.matcher(source);
            while (matcher.find()) {
                // 统一补全为规范格式（带分号）
                imports.add("import " + matcher.group(1) );
            }
        }
        StringBuilder  sb = new StringBuilder();
        for (String importSeg : imports) {
            sb.append(importSeg).append("\n");
        }
        return sb.toString();
    }

    // 生成组件/菱形框的实际代码
    // 生成组件/菱形框的实际代码（移除循环相关逻辑，并增加分支限制）
    private void generateComponentBody(String elementId,
                                       Map<String, JSONObject> components,
                                       Map<String, JSONObject> diamonds,
                                       JSONArray connections,
                                       StringBuilder groovy,
                                       Set<String> processed) {
        if (processed.contains(elementId)) return;
        processed.add(elementId);

        // 处理组件
        if (components.containsKey(elementId)) {
            JSONObject component = components.get(elementId);
            String objectType = component.getString("objectType");
            if(IBusinessConstant.NODE_TYPE_COMPONENT.equals(objectType)) {
                JSONObject textAttrs = component.getJSONArray("children").getJSONObject(2).getJSONObject("attrs");

                String className = getSimpleClassName(textAttrs.getString("className"));
                String method = textAttrs.getString("selectedFunctionPoint");
                String returnVar = textAttrs.getString("returnValueName");
                JSONArray params = textAttrs.getJSONArray("functionPointParams");

                // 生成方法调用代码
                groovy.append("        // 组件: ").append(elementId).append("\n");
                if (StringUtils.isNotEmpty(returnVar)) {
                    groovy.append("        def ").append(returnVar).append(" = ");
                } else {
                    groovy.append("        ");
                }
                groovy.append(className).append(".").append(method).append("(");
                appendParams(groovy, params);
                groovy.append(")\n\n");

                // 处理出向连接
                processOutgoingConnections(elementId, components, diamonds, connections,
                        groovy, processed);

            } else if(IBusinessConstant.NODE_TYPE_RETURN.equals(objectType)){
                groovy.append("        // 节点: ").append(elementId).append("\n");
                String returnVar = component.getString("returnValue");
                groovy.append("        return ").append(returnVar).append("\n\n");
            }

        }
        // 处理菱形节点
        else if (diamonds.containsKey(elementId)) {
            // 收集所有出向连接
            List<JSONObject> outgoing = new ArrayList<>();
            for (int i = 0; i < connections.size(); i++) {
                JSONObject conn = connections.getJSONObject(i);
                if (elementId.equals(conn.getString("startElementId"))) {
                    outgoing.add(conn);
                }
            }

            // 添加分支数量限制检查
            if (outgoing.size() > 2) {
                throw new RuntimeException("菱形节点 " + elementId + " 的分支数不能超过2个");
            }

            // 生成条件分支
            boolean hasConditions = false;
            for (JSONObject conn : outgoing) {
                if (StringUtils.isNotEmpty(conn.getString("condition"))) {
                    hasConditions = true;
                    break;
                }
            }

            if (hasConditions) {
                // 先生成条件为true的分支
                for (JSONObject conn : outgoing) {
                    String condition = conn.getString("condition");
                    if (condition != null && !condition.startsWith("!")) {
                        groovy.append("        if (").append(condition).append(") {\n");
                        generateComponentCode(conn.getString("endElementId"),
                                components, diamonds, connections,
                                groovy, new HashSet<>(processed));
                        groovy.append("        }\n");
                    }
                }

                // 然后生成条件为false的分支
                for (JSONObject conn : outgoing) {
                    String condition = conn.getString("condition");
                    if (condition != null && condition.startsWith("!")) {
                        groovy.append("        else {\n");
                        generateComponentCode(conn.getString("endElementId"),
                                components, diamonds, connections,
                                groovy, new HashSet<>(processed));
                        groovy.append("        }\n");
                        break; // 只需要一个else分支
                    }
                }

                // 如果只有一个条件分支，生成默认else分支
                long conditionCount = outgoing.stream()
                        .map(conn -> conn.getString("condition"))
                        .filter(StringUtils::isNotEmpty)
                        .count();

                if (conditionCount == 1 && outgoing.size() == 2) {
                    // 检查是否有一个是空条件
                    boolean hasEmptyCondition = outgoing.stream()
                            .anyMatch(conn -> StringUtils.isEmpty(conn.getString("condition")));

                    if (hasEmptyCondition) {
                        groovy.append("        else {\n");
                        // 找到没有条件的连接
                        for (JSONObject conn : outgoing) {
                            if (StringUtils.isEmpty(conn.getString("condition"))) {
                                generateComponentCode(conn.getString("endElementId"),
                                        components, diamonds, connections,
                                        groovy, new HashSet<>(processed));
                                break;
                            }
                        }
                        groovy.append("        }\n");
                    }
                }
            } else {
                // 无条件分支（最多两个分支）
                int branchCount = 0;
                for (JSONObject conn : outgoing) {
                    if (++branchCount > 2) {
                        throw new RuntimeException("菱形节点 " + elementId + " 的分支数不能超过2个");
                    }
                    generateComponentCode(conn.getString("endElementId"),
                            components, diamonds, connections,
                            groovy, new HashSet<>(processed));
                }
            }
        }
    }
    // 处理出向连接（移除循环相关逻辑）
    private void processOutgoingConnections(String currentId,
                                            Map<String, JSONObject> components,
                                            Map<String, JSONObject> diamonds,
                                            JSONArray connections,
                                            StringBuilder groovy,
                                            Set<String> processed) {
        List<JSONObject> outgoing = new ArrayList<>();

        // 收集所有出向连接（只处理有效连接）
        for (int i = 0; i < connections.size(); i++) {
            JSONObject conn = connections.getJSONObject(i);
            if (currentId.equals(conn.getString("startElementId")) &&
                    isValidElement(conn.getString("endElementId"), diamonds, components)) {
                outgoing.add(conn);
            }
        }

        // 处理所有有效出向连接
        for (JSONObject conn : outgoing) {
            generateComponentCode(conn.getString("endElementId"),
                    components, diamonds, connections,
                    groovy, new HashSet<>(processed));
        }

        //如果没有出向连接，则生成一个默认的结束代码
        if (outgoing.isEmpty()) {
            groovy.append("        return \n");
        }
    }

    // 新增方法：检查元素ID是否有效
    private boolean isValidElement(String elementId,
                                   Map<String, JSONObject> diamonds,
                                   Map<String, JSONObject> components) {
        if (elementId == null || elementId.isEmpty()) {
            return false;
        }
        return diamonds.containsKey(elementId) || components.containsKey(elementId);
    }
    /**
     * 获取简单类名，不包含包名
     * @param className
     * @return
     */
    private String getSimpleClassName(String className) {
        int lastDotIndex = className.lastIndexOf(".");
        if (lastDotIndex != -1) {
            return className.substring(lastDotIndex + 1);
        } else {
            return className;
        }
    }
    // 辅助方法：追加参数
    private void appendParams(StringBuilder groovy, JSONArray params) {
        if (params != null) {
            for (int i = 0; i < params.size(); i++) {
                JSONObject param = params.getJSONObject(i);
                groovy.append(param.getString("value"));
                if (i < params.size() - 1) groovy.append(", ");
            }
        }
    }
    /**
     * 复合模式更新
     *
     * @param businessComponentComposite
     * @return
     */
    @Override
    public Long updateBusinessComponentComposite(BusinessComponentComposite businessComponentComposite) {
        //判断当前主表状态
        //如果是草稿，则更新
        if(IBusinessConstant.STATUS_DRAF.equals(businessComponentComposite.getBusinessComponent().getStatus())){
            //简单更新即可
            businessComponentMapper.updateBusinessComponent(businessComponentComposite.getBusinessComponent());
            //删除原来参数，再插入参数
            businessComponeParametersVersionService.deleteParametersVersionByComponentCode(
                    businessComponentComposite.getBusinessComponent().getComponentCode(),
                    businessComponentComposite.getBusinessComponent().getEnterpriseCode(),
                    businessComponentComposite.getBusinessComponent().getVersion()
            );
            for (BusinessComponeParametersVersion businessComponeParametersVersion : businessComponentComposite.getBusinessComponeParametersVersions()) {
                businessComponeParametersVersionService.insertBusinessComponeParametersVersion(businessComponeParametersVersion);
            }
            //删除原来返回值列表，再插入返回值
//            businessComponentReturnValueVersionService.deleteReturnValueVersionByComponentCode(
//                    businessComponentComposite.getBusinessComponent().getComponentCode(),
//                    businessComponentComposite.getBusinessComponent().getEnterpriseCode(),
//                    businessComponentComposite.getBusinessComponent().getVersion()
//            )
            //如果是已提交，则然后更新当前主表记录为非当前版本,版本号加1,插入主表记录，然后插入功能点版本表及参数表
        }else{
            businessComponentComposite.getBusinessComponent().setIsCurrent(IBusinessConstant.SYSTEM_NO);
            //版本号+1
            fillUpdateDefaultValues(businessComponentComposite);
            businessComponentMapper.updateBusinessComponent(businessComponentComposite.getBusinessComponent());
            businessComponentComposite.getBusinessComponent().setId(0L);
            businessComponentComposite.getBusinessComponent().setIsCurrent(IBusinessConstant.SYSTEM_YES);
            //主表状态设置为草稿
            businessComponentComposite.getBusinessComponent().setStatus(IBusinessConstant.STATUS_DRAF);
            businessComponentMapper.insertBusinessComponent(businessComponentComposite.getBusinessComponent());
            businessComponentComposite.getBusinessComponent().setIsCurrent("N");
            for (BusinessComponeParametersVersion businessComponeParametersVersion : businessComponentComposite.getBusinessComponeParametersVersions()) {
                businessComponeParametersVersionService.insertBusinessComponeParametersVersion(businessComponeParametersVersion);
            }
        }
        return businessComponentComposite.getBusinessComponent().getId();
    }

    /**
     * 复合模式插入
     *
     * @param businessComponentComposite
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long insertBusinessComponentComposite(BusinessComponentComposite businessComponentComposite) {
        fillInsertDefaultValues(businessComponentComposite);
        //主表状态设置为草稿
        businessComponentComposite.getBusinessComponent().setStatus(IBusinessConstant.STATUS_DRAF);
        //插入基本信息
        businessComponentComposite.getBusinessComponent().setIsCurrent("N");
        businessComponentMapper.insertBusinessComponent(businessComponentComposite.getBusinessComponent());
        //插入组件参数信息
        for (BusinessComponeParametersVersion businessComponeParametersVersion : businessComponentComposite.getBusinessComponeParametersVersions()) {
            businessComponeParametersVersionService.insertBusinessComponeParametersVersion(businessComponeParametersVersion);
        }
        //插入组件返回值信息
        for (BusinessComponentReturnValueVersion businessComponeReturnVersion : businessComponentComposite.getBusinessComponentReturnValueVersions()) {
            businessComponentReturnValueVersionService.insertBusinessComponentReturnValueVersion(businessComponeReturnVersion);
        }
        return businessComponentComposite.getBusinessComponent().getId();
    }
}
